'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState, useEffect } from 'react';
import { Toaster } from 'react-hot-toast';
import { ChainProvider } from '@/context/ChainContext';
import { AuthInitializer } from '@/components/auth/AuthInitializer';
import { I18nextProvider } from 'react-i18next';
import i18n from '@/lib/i18n';

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(() => new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 60 * 1000, // 1 minute
        retry: 1,
      },
    },
  }));

  // Initialize language from localStorage after hydration
  useEffect(() => {
    const savedLanguage = localStorage.getItem('dtv-language');
    if (savedLanguage && (savedLanguage === 'en' || savedLanguage === 'zh')) {
      i18n.changeLanguage(savedLanguage);
    }

    const handleStorageChange = () => {
      const newLanguage = localStorage.getItem('dtv-language');
      if (newLanguage && (newLanguage === 'en' || newLanguage === 'zh')) {
        i18n.changeLanguage(newLanguage);
      }
    };

    // Listen for storage changes from other tabs
    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <I18nextProvider i18n={i18n}>
        <ChainProvider>
          <AuthInitializer>
            {children}
          </AuthInitializer>
          <Toaster 
            position="top-right"
            toastOptions={{
              duration: 4000,
              style: {
                background: '#363636',
                color: '#fff',
              },
              success: {
                iconTheme: {
                  primary: '#10b981',
                  secondary: '#fff',
                },
              },
              error: {
                iconTheme: {
                  primary: '#ef4444',
                  secondary: '#fff',
                },
              },
            }}
          />
        </ChainProvider>
      </I18nextProvider>
    </QueryClientProvider>
  );
}